<template>
  <div class="idle-classroom">
    <!-- 筛选条件 -->
    <condition-card :label-width="'130px'" @reset="reset" @search="onSubmit">
      <el-row>
        <el-col :span="8">
          <el-form-item :label="$t('classroom.type')">
            <DictSelect
              :plzSelect="true"
              v-model="query.type"
              :clearable="true"
              :data="options.type"
            ></DictSelect>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('classroom.campus')">
            <DictSelect
              :plzSelect="true"
              v-model="query.campus"
              :data="options.campus"
              :clearable="true"
              @change="handelCampusChang"
            ></DictSelect>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('classroom.tower')">
            <DictSelect
              :plzSelect="true"
              v-model="query.towerCode"
              :clearable="true"
              :filterable="true"
              :data="teachingBuildingArr"
            ></DictSelect>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item :label="$t('classroom.floor')">
            <el-input
              type="text"
              v-model="query.floor"
              :placeholder="$t('message.plzSelect')"
              @keypress.native="checkNum"
              maxlength="5"
              />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('classroom.classCapacity1')" >
            <el-input type="text" v-model="query.classCapacity" :placeholder="$t('message.mustNumber')" maxlength="5" @keypress.native="checkNum"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('classroom.examCapacity1')" >
            <el-input type="text" v-model="query.examCapacity" :placeholder="$t('message.mustNumber')" maxlength="5" @keypress.native="checkNum"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item :label="$t('classroom.name')" >
            <el-input type="text" v-model="query.name" :placeholder="$t('message.plsInput')"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('classroom.teachingWeek')">
            <el-row>
              <el-col :span="10">
                <el-input type="text" style="width: 100%;" v-model="query.weekStart" @keypress.native="checkNum" @blur="checkWeekValue($event,1)" :placeholder="$t('message.mustNumber')"/>
              </el-col>
              <div class="text-center float-left plr-15px">-</div>
              <el-col :span="10"> 
                <el-input type="text" style="width: 100%;" v-model="query.weekEnd" @keypress.native="checkNum" @blur="checkWeekValue($event,2)" :placeholder="$t('message.mustNumber')"/>
              </el-col>
              <div class="text-center float-left pl-15px">{{$t('classroom.week')}}</div>
            </el-row>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('label.schoolTerm')">
            <CalendarSelect v-model="query.calendarId" :all="true" :defaulted ="true" @change="changeCalendar" @load-done="calendarLoadDone"></CalendarSelect>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item  :label="$t('classroom.dayOfWeekByClassroom')" >
            <el-row>
              <el-col :span="8">
                <DictSelect
                  :plzSelect="true"
                  v-model="query.dayOfWeekStart"
                  :data="options.week"
                  :clearable="true"
                  :exclude="dayOfWeekStartExclude"
                  @change="changeDayOfWeekEndExclude"
                ></DictSelect>
              </el-col>
              <div class="text-center float-left plr-15px">-</div>
              <el-col :span="8">
                <DictSelect
                  :plzSelect="true"
                  v-model="query.dayOfWeekEnd"
                  :data="options.week"
                  :clearable="true"
                  :exclude="dayOfWeekEndExclude"
                  @change="changeDayOfWeekStartExclude"
                ></DictSelect>
              </el-col>
            </el-row>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item  label="教室使用小节" >
            <el-row>
              <el-col  :span="8">
                <el-input  type="text" v-model="query.timeStart"  @keypress.native="checkNum" @blur="checkTimeValue($event,1)" :placeholder="$t('message.mustNumber')"/>  
              </el-col>
              <div class="text-center float-left plr-15px">-</div>
              <el-col  :span="8">
                <el-input type="text" v-model="query.timeEnd"  @keypress.native="checkNum" @blur="checkTimeValue($event,2)" :placeholder="$t('message.mustNumber')"/> 
              </el-col>
              <div class="pl-15px text-center" style="color: #999999d6;">{{$t("classroomCheckTips.timeSessionRange")}}</div>
            </el-row>
          </el-form-item>
        </el-col>
      </el-row>
    </condition-card>
    <!-- 基本信息列表 -->
    <el-card shadow="never">
      <div class="edu-opertion-bar">
        <h2>{{$t("classroomTower.viewFreeClassroom")}}</h2>
        <el-input
          v-model="query.conditionValue"
          :placeholder="$t('classroomCheckTips.plzInputClassroomName')"
          suffix-icon="el-icon-search"
          style="width:240px"
          @keyup.enter.native="onSubmit"
        />
      </div>
      <EduTable
        :order="true"
        :selection="false"
        :data="idleRoomList.data"
        :total="idleRoomList.total"
        :pageSize="query.pageSize_"
        :current-page="query.pageNum_"
        @page-change="pageChange"
        @selection-change="handleSelectionChange"
      >
        <el-table-column :label="$t('classroom.name')">
          <template slot-scope="scope">
            <el-tooltip placement="top" :content="scope.row.name" effect="light">
              <el-button type="text" @click="openClassroomDetails(scope.row)">{{scope.row.name}}</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column :label="$t('classroom.tower')" >
          <template slot-scope="scope">{{scope.row.towerName}}</template>
        </el-table-column>
        <el-table-column :label="$t('classroom.floor')">
          <template slot-scope="scope">{{scope.row.floor}}</template>
        </el-table-column>
        <el-table-column :label="$t('classroom.maxRow')">
          <template slot-scope="scope">{{scope.row.maxRow}}</template>
        </el-table-column>
        <el-table-column :label="$t('classroom.maxCol')">
          <template slot-scope="scope">{{scope.row.maxCol}}</template>
        </el-table-column>
        <el-table-column :label="$t('classroom.campus')">
          <template slot-scope="scope">{{scope.row.campusI18n}}</template>
        </el-table-column>
        <el-table-column :label="$t('classroom.type')">
          <template slot-scope="scope">{{scope.row.typeI18n}}</template>
        </el-table-column>
        <el-table-column :label="$t('classroom.classCapacity')">
          <template slot-scope="scope">{{scope.row.classCapacity}}</template>
        </el-table-column>
        <el-table-column :label="$t('classroom.examCapacity')">
          <template slot-scope="scope">{{scope.row.examCapacity}}</template>
        </el-table-column>
      </EduTable>
    </el-card>
    <!-- 教室详细信息 -->
    <edu-dialog
      ref="classroomDetailDialog"
      class="classroomDetailDialog"
      :title="$t('classroom.classroomDetail')"
      :showButtons="false"
    >
      <room-info-details :classroomDetail="classroomDetail" />
    </edu-dialog>
  </div>
</template>

<script>
import { queryDic } from "common/src/api/dictionary";
import * as API from "common/src/api/resource/classroom";
import UTILS from "common/src/utils/utils";
import roomInfoDetails from "./components/roomInfoDetails";
export default {
  name: "idleClassroom",
  components: {
    roomInfoDetails
  },
  data() {
    return {
      query: {
        pageNum_: 1,
        pageSize_: 20,
        type: "",
        campus: "",
        towerCode: "",
        floor: "",
        examCapacity: "",
        classCapacity: "",
        weekStart: "",
        weekEnd: "",
        calendarId: "",
        dayOfWeekStart: "",
        dayOfWeekEnd: "",
        timeStart:"",
        timeEnd: "",
        timeStart2:"",
        timeEnd2: "",
        
        conditionValue: ""
      },
      teachingBuildingArr: [],
      defaultQuery: {
        pageNum_: 1,
        pageSize_: 20,
        type: "",
        campus: "",
        towerCode: "",
        floor: "",
        examCapacity: "",
        classCapacity: "",
        weekStart: "",
        weekEnd: "",
        calendarId: "",
        dayOfWeekStart: "",
        dayOfWeekEnd: "",
        timeStart:"",
        timeEnd: "",
        timeStart2:"",
        timeEnd2: "",
        conditionValue: ""
      },
      options: {
        type: [],
        campus: [],
        week: [
          {
            label: "星期一",
            value: "1",
            disabled: true
          },
          {
            label: "星期二",
            value: "2",
            disabled: true
          },
          {
            label: "星期三",
            value: "3"
          },
          {
            label: "星期四",
            value: "4"
          },
          {
            label: "星期五",
            value: "5"
          },
          {
            label: "星期六",
            value: "6"
          },
          {
            label: "星期日",
            value: "7"
          }
        ]
      },
      idleRoomList: {
        data: [],
        total: 0
      },
      // 教室详情信息
      classroomDetail: {},
      currentTermCalendar:'',
      //所有校历数据
      allCalendarList:[],
      //当前学期下的总教学周
      totalWeekNumber:'',
      //可输入最大节次
      maxTime : 12,
      //可输入最小节次
      minTime : 1,
      //教室使用时间类型
      //做教室使用星期选择校验
      dayOfWeekStartExclude:[],
      dayOfWeekEndExclude:[]

    }; 
  },
  methods: {
    changeDayOfWeekEndExclude(val){
      let tempList = [];
      for (let index = 0; index < (parseInt(val)-1); index++) {
        tempList.push(index+1);
      }
      this.dayOfWeekEndExclude = tempList;
    },
    changeDayOfWeekStartExclude(val){
      let tempList = [];
      for (let index = 7; val && index > val; index--) {
        tempList.push(index);
      }
      this.dayOfWeekStartExclude = tempList;
    },
    calendarLoadDone(list){
			if(list) {
        this.allCalendarList = list;
			 for (let index = 0; index < list.length; index++) {
				 const element = list[index];
				 if (element.currentTermFlag) {
          this.currentTermCalendar = element.id;
          this.totalWeekNumber = element.weekNum;
					break;
				}
			 }
			}
    },
    //每当校历发生变化，动态加载教学周总量
    changeCalendar(val){
      if (this.allCalendarList){
        this.allCalendarList.forEach(canlendar =>{
            if(canlendar.id === val){
              this.totalWeekNumber = canlendar.weekNum;
            }
        })
      }
    },
    // 获取下拉框数据（数据字典）
    initOptions() {
      let data = {
        lang: this.$store.getters.language || "cn",
        type: "allChild",
        keys: ["X_YX", "X_XQ", "X_JSLX", "X_GLBM"]
      };
      queryDic(data).then(res => {
        if (res.code == 200) {
          UTILS.fillSelect(
            {
              campus: "X_XQ",
              departmentCode: "X_YX",
              type: "X_JSLX",
              fixedDept: "X_YX",
              dept: "X_GLBM"
            },
            res.data,
            this.options
          );
        }
      });
    },
    //把部门list 转换成字符串
    getDepartmentStrByList(list) {
      let str = "";
      if (list != null) {
        list.forEach(index => {
          str += index.departmentCodeI18n + " |";
        });
        str = str.substr(0, str.length - 1);
      }
      return str;
    },
    //把用途list 转换成字符串
    getUsageStrByList(list) {
      let str = "";
      if (list != null) {
        list.forEach(index => {
          str += index.usageCodeI18n + " |";
        });
        str = str.substr(0, str.length - 1);
      }
      return str;
    },
    //把所属部门list 转换成字符串
    getProjectStrByList(list) {
      let str = "";
      if (list != null) {
        list.forEach(index => {
          str += index.projectIdI18n + " |";
        });
        str = str.substr(0, str.length - 1);
      }
      return str;
    },
    async getFreeClassroomInfoList(){
      
      //1 保证提交的数据中周次必须起始周和结束周要么都有值，要么都没值
      if (this.query.weekStart) {
        if (this.query.weekEnd == "" || this.query.weekEnd == 0) {
          this.query.weekEnd = this.totalWeekNumber;
        }
      }
      if (this.query.weekEnd) {
        if (this.query.weekStart == "" || this.query.weekStart == 0) {
          this.query.weekStart = 1;
        }
      }
      if (this.query.weekStart > 0 && this.query.weekEnd > 0 && (parseInt(this.query.weekEnd) < parseInt(this.query.weekStart))) {
        this.$message({
              type: "warning",
              message: "筛选条件起始周次不能大于结束周次!"
            });
        return;
      }
      //3 保证提交的数据中节次必须起始值和结束值要么都有值，要么都没值
      if (this.query.timeStart) {
        if (this.query.timeEnd == "" || this.query.timeEnd == 0) {
          this.query.timeEnd = this.maxTime;
        }
      }
      if (this.query.timeEnd) {
        if (this.query.timeStart == "" || this.query.timeStart == 0) {
          this.query.timeStart = 1;
        }
      }
      if (this.query.timeStart > 0 && this.query.timeEnd > 0 && parseInt(this.query.timeEnd) < parseInt(this.query.timeStart)) {
        this.$message({
              type: "warning",
              message: "筛选条件起始节次不能大于结束节次!"
            });
        return;
      }
      let res = await API.getFreeClassroomInfoList(this.query);
      // 对固定使用部门数据进行处理
      if (res && res.code == 200) {
        _.forEach(res.data.list, item => {
          item.departmentStr = this.getDepartmentStrByList(
            item.fixDepartmentList
          );
          item.usageStr = this.getUsageStrByList(item.classroomUsageList);
          item.projectStr = this.getProjectStrByList(item.belongDepartmentList);
          item.fixDepartmentList = item.fixDepartmentList.map(item => {
            return item.departmentCode;
          });
          item.belongDepartmentList = item.belongDepartmentList.map(item => {
            return item.projectId;
          });
          item.classroomUsageList = item.classroomUsageList.map(item => {
            return item.usageCode;
          });
        });
        this.idleRoomList.data = res.data.list;
        this.idleRoomList.total = res.data.total_;
        this.query.pageSize_ = res.data.pageSize_;
        this.query.pageNum_ = res.data.pageNum_;
      }
    },
    handelCampusChang(item) {
      this.teachingBuildingArr = [];
      this.query.towerCode = "";
      let params = {
        campus: item
      };
      API.conditionQueryByDict(params).then(res => {
        _.forEach(res.data.list, item => {
          this.teachingBuildingArr.push({
            value: item.code,
            label: item.name
          });
        });
      });
    },
    // 分页功能
    pageChange(val) {
      this.query.pageNum_ = val.pageNum;
      this.query.pageSize_ = val.pageSize;
      this.getFreeClassroomInfoList();
    },
    // 重置筛选条件
    reset() {
      this.query = JSON.parse(JSON.stringify(this.defaultQuery));
      //学期为当前学期
      this.query.calendarId = this.currentTermCalendar;
      this.getFreeClassroomInfoList();
      this.handelCampusChang(null);
    },
    onSubmit() {
      this.getFreeClassroomInfoList();
    },
    // 打开查看教室详情
    openClassroomDetails(info) {
      this.$refs.classroomDetailDialog.open();
      let cloneInfo = _.clone(info);
      this.classroomDetail = cloneInfo;
    },
    checkNum(e) {
      //只输入数字正则
      let reg = /^(0|[1-9]\d*)$/;
      let num = e.target.value || "";
      let str =
        e.key && e.key != "Unidentified" ? e.key : num.substr(num.length - 1);
      //没有满足任何一种情况，中断执行
      if (reg.test(str)) {
        return true;
      }
      e.returnValue = false;
      return false;
    },
    checkTimeValue(e,flag) {
      let inputValue = e.target.value;
      if(inputValue > this.maxTime) {
          e.target.value = this.maxTime;
          if (flag === 1) {
              this.query.timeStart = this.maxTime;
          } else {
            this.query.timeEnd = this.maxTime;
          } 
      }
    },
    checkWeekValue(e,flag) {
      let inputValue = e.target.value;
      if(inputValue > this.totalWeekNumber) {
          e.target.value = this.totalWeekNumber;
          if (flag === 1) {
              this.query.weekStart = this.totalWeekNumber;
          } else {
            this.query.weekEnd = this.totalWeekNumber;
          } 
      }
    }
  },
  created() {
    this.initOptions();
    this.getFreeClassroomInfoList();
    this.handelCampusChang(null);
  },
  watch:{
   
  }
};
</script>

<style lang="scss" scoped>
.idle-classroom {
  .plr-15px {
    padding: 0 6px;
  }
  .pl-15px {
    padding-left: 5px;
  }
}
</style>
